package org.samith.dao;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import org.samith.entity.Subscriber;
import org.samith.entity.User;

@Stateless
public class SubscriberDaoImpl extends BaseDaoImpl<Subscriber> implements SubscriberDao {

	@EJB
	UserDao userDao;
	
	@Override
	public Class<Subscriber> getType() {
		return Subscriber.class;
	}

	@Override
	public Subscriber findByPhoneNumber(String phoneNumber) {
		Query query = em.createQuery("SELECT a FROM Subscriber a WHERE a.phoneNumber = :p ");
		query.setParameter("p", phoneNumber);
		Subscriber subscriber;
		try{
			subscriber = (Subscriber) query.getSingleResult();
			if(subscriber != null)
				return subscriber;
			else
				return null;
		}catch(NoResultException ex){
			return null;
		}
	}

	@Override
	public Subscriber findByUserId(Long userId) {
		Query query = em.createQuery("SELECT a FROM Subscriber a WHERE a.userId = :u ");
		User usr = (User) userDao.findById(userId);
		System.out.println("========= user is "+usr + " ===== ");
		query.setParameter("u", usr);
		Subscriber subscriber;
		try{
			subscriber = (Subscriber) query.getSingleResult();
			if(subscriber != null)
				return subscriber;
			else
				return null;
		}catch(NoResultException ex){
			return null;
		}
	}
	 
}
